package com.sanerzone.smscenter.config.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.sanerzone.common.support.sequence.MsgId;
import com.sanerzone.smscenter.biz.VerifyInterface.GatewayMatch;
import com.sanerzone.smscenter.biz.VerifyInterface.impl.GatewayMatchImpl;
import com.sanerzone.smscenter.biz.cache.AccountCacheHelper;
import com.sanerzone.smscenter.biz.cache.GatewayQueueHelper;
import com.sanerzone.smscenter.biz.cache.GatewayRelHelper;
import com.sanerzone.smscenter.biz.entity.SmsGateway;
import com.sanerzone.smscenter.biz.entity.SmsSend;
import com.sanerzone.smscenter.biz.entity.SmsSendVo;
import com.sanerzone.smscenter.biz.entity.TopicQueue;
import com.sanerzone.smscenter.biz.iface.SMSSaleInterface;
import com.sanerzone.smscenter.biz.iface.SmsTaskInterface;
import com.sanerzone.smscenter.biz.iface.WebServiceInterface;
import com.sanerzone.smscenter.biz.listener.SMSREQListener;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSREQMessage;
import com.sanerzone.smscenter.biz.message.SMSURREQMessage;
import com.sanerzone.smscenter.biz.service.impl.SmsSendServiceImpl;
import com.sanerzone.smscenter.biz.service.impl.SmsTaskServiceImpl;
import com.sanerzone.smscenter.biz.utils.DateHelper;
import com.sanerzone.smscenter.biz.utils.StringHelper;
import com.sanerzone.smscenter.biz.utils.TableNameHelper;
import com.sanerzone.smscenter.common.tools.MQHelper;
import com.sanerzone.smscenter.common.tools.SpringContextHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class SmsSaleInterfaceImpl implements SMSSaleInterface{
	public static Logger logger = LoggerFactory.getLogger(SmsSaleInterfaceImpl.class);

	@Autowired
	private SmsSendServiceImpl smsSendService;

	@Autowired
	private WebServiceInterfaceImpl webServiceInterfaceImpl;

	@Autowired
	public MQHelper mQUtils;



	private GatewayMatch gatewayMatch=new GatewayMatchImpl();
	/**
	 *
	 * @param type   操作，1,审核
	 * @param sendStatus  短信状态 T000成功，V000审核，F000失败
	 * @param ids sms_sned表 ids，id之间用逗号分隔
	 * @return
	 */
	//这里只是单一的完成让订单失败的操作
	@Override
	public boolean setSMSstatus(int type, String sendStatus, String ids,String content){
		SqlSession sqlSession = SpringContextHelper.getBean(SqlSessionFactory.class).openSession();
		int index=0;
		boolean flag =  true;
		if (Strings.isNullOrEmpty(ids)) {
			return  false;
		}
		String[] smsIds = ids.split(";");
		for (int i = 0; i < smsIds.length; i++) {

			String idTemp=smsIds[i];
			Map map=new HashMap( );
			map.put( "id",idTemp );
			map.put("tableName", TableNameHelper.getSmsSendTable(idTemp));
			SmsSend smsSend=smsSendService.getById( map );
			smsSend.setSendStatus( sendStatus );
			if (StringUtils.isNotBlank( content )){
				smsSend.setSmsContent( content );
			}
			SmsSendVo smsSendVo=new SmsSendVo();

			BeanUtils.copyProperties(smsSend,smsSendVo  );
			boolean sendFlag=false;
			if (sendStatus.startsWith( "F" )){
				if(smsSendVo.getShowLevel().equals( "2" )){
					//分割订单，发送至MT
					sendFlag=webServiceInterfaceImpl.setFalseSendMt( smsSendVo );
					if (sendFlag==false) {
						flag = false;
					}else{
						smsSendService.setStatusFalse( map );
					}
				}else{
					//如果是单条明细设置失败，只要修改单条记录状态即可
					Map<String, Object> map1 = Maps.newHashMap();
					map1.put( "mtBatch", smsSendVo.getMtBatch());
					map1.put( "phone", smsSendVo.getPhone() );
					map1.put( "gatewayStatus", "F1010" );
					map1.put( "tableName", TableNameHelper.getSmsSendTable( idTemp ));
					map1.put( "sendStatus","F000" );
					map1.put( "failReason","后台审核不通过" );

					int count=sqlSession.update( "com.sanerzone.smscenter.biz.mapper.SmsSendMapper.batchUpdateGatewayStatusByPhone", map1 );
					if (count>0){
						index++;
					}
					if (count%500==0){
						sqlSession.commit();
					}
					String needReport=StringHelper.registeredDelivery(AccountCacheHelper.getStringValue(smsSendVo.getUserid()+"_"+smsSendVo.getAccId(), "callbackUrl",
							""))?"1":"0";
					if ("1".equals( needReport )){
						//将这条失败推送给用户
						SMSURREQMessage sMSURREQMessage = new SMSURREQMessage();
						sMSURREQMessage.setAccid( smsSendVo.getAccId() );
						sMSURREQMessage.setBizid( smsSendVo.getId() );
						sMSURREQMessage.setDoneTime( DateHelper.formatCmppDate( smsSendVo.getSubmitTime() ) );
						sMSURREQMessage.setGateWayId( smsSendVo.getGatewayId() );
						sMSURREQMessage.setMsgid( smsSendVo.getMtBatch() );
						sMSURREQMessage.setPhone( smsSendVo.getPhone() );
						sMSURREQMessage.setSourceGateWayId( smsSendVo.getSourceGatewayId() );
						sMSURREQMessage.setSpnumber( smsSendVo.getSpnumber());
						sMSURREQMessage.setStat( smsSendVo.getWaitReason() );
						sMSURREQMessage.setSubmitTime( DateHelper.formatCmppDate( smsSendVo.getSubmitTime() ));
						sMSURREQMessage.setTaskid(smsSendVo.getTaskid());
						sMSURREQMessage.setUserid( smsSendVo.getUserid() );
						sMSURREQMessage.setMessageid( smsSendVo.getCustomServiceid() );
						mQUtils.sendSmsUR( smsSendVo.getId(), sMSURREQMessage );
					}
				}

			} else {//设置订单成功

				sendFlag = webServiceInterfaceImpl.doCheck( smsSendVo );
				if (sendFlag) {
					webServiceInterfaceImpl.setOrderLoseEfficacy( smsSendVo );

				} else {
					flag = false;
				}
			}

			}
		if (sqlSession!=null){
			sqlSession.close();
		}
		return flag;
	}

	public static String getTableIndex(String bizid){
		if (StringUtils.isNotBlank(bizid)){
			return String.valueOf(new MsgId(bizid).getDay());
		}else{
			return "";
		}
	}
}
